package cn.aopmin.java.api.util.concurrent.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 同步锁的使用
 * @author 白豆五
 * @since 2025/1/30
 */
public class LockTest {
    public static void main(String[] args) {

        // 创建售票任务对象
       TicketWindow4 ticketWindow = new TicketWindow4();

        // 模拟4个窗口
        Thread window1 = new Thread(ticketWindow, "窗口1：");
        Thread window2 = new Thread(ticketWindow, "窗口2：");
        Thread window3 = new Thread(ticketWindow, "窗口3：");
        Thread window4 = new Thread(ticketWindow, "窗口4：");

        window1.start();
        window2.start();
        window3.start();
        window4.start();

    }
}

/**
 * 售票任务
 */
class TicketWindow4 implements Runnable {
    // lock锁对象
    private static final Lock lock= new ReentrantLock();

    /**
     *  100张票，共享变量， 由4个线程共享
     */
    int ticket = 100;

    /**
     * 售票, 没有考虑线程安全问题
     */
    @Override
    public void run() {
        lock.lock();
        try {
            while (ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String msg = String.format("%s正在出售第%s张票", Thread.currentThread().getName(), ticket);
                System.out.println(msg);
                ticket--;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}